<template>
  <div class="pagination">
    <button :disabled="pageNo == 1" @click="$emit('getpage', pageNo - 1)">
      上一页
    </button>
    <!-- //!!!!传输数据给需要分页器的组件 -->
    <button
      v-show="startNumAndEndNum.start > 1"
      @click="$emit('getpage', 1)"
      :class="{ active: pageNo == 1 }"
    >
      1
    </button>
    <button v-show="startNumAndEndNum.start > 2">...</button>

    <!--    //!!遍历数字 隐藏不需要的页码 -->
    <button
      v-for="(list, index) in startNumAndEndNum.end"
      :key="index"
      v-show="list >= startNumAndEndNum.start"
      @click="$emit('getpage', list)"
      :class="{ active: pageNo == list }"
    >
      {{ list }}
    </button>

    <button v-show="startNumAndEndNum.end < totalPage - 1">···</button>
    <button
      v-show="startNumAndEndNum.end < totalPage"
      @click="$emit('getpage', totalPage)"
      :class="{ active: pageNo == totalPage }"
    >
      {{ totalPage }}
    </button>
    <button
      :disabled="pageNo == totalPage"
      @click="$emit('getpage', pageNo + 1)"
    >
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ totalPage }} 页</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  //自己定义使用分页器
  props: ["pageNo", "pageContain", "total", "continues"],
  computed: {
    //!!!下面代码可以多写几遍 练习逻辑思维能力
    //计算总的页码数
    totalPage() {
      return Math.ceil(this.total / this.pageContain);
    },
    //计算出连续的页码的起始数字和结束数字（这里search传过来的连续页码数为5）
    startNumAndEndNum() {
      const { continues, pageNo, totalPage } = this;
      let start = 0;
      let end = 0;
      if (continues > totalPage) {
        start = 1;
        end = totalPage;
      } else {
        start = pageNo - parseInt(continues / 2);
        end = pageNo + parseInt(continues / 2);
        if (start < 1) {
          start = 1;
          end = continues;
        } else if (end > totalPage) {
          end = totalPage;
          start = totalPage - continues + 1;
        }
      }
      //验证end 和start的值
      // console.log(end, start);
      //返回的是一个对象  v-k一致，省略k
      return { start, end };
    },
  },
};
</script>

<style scoped lang="less">
.active {
  background-color: #409eff;
}
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>